package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.JsonResult;
import cn.wolfcode.exception.LogicException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;
@Service
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private  EmployeeMapper employeeMapper;
    @Override
    @Transactional
    public void delete(Long id) {
        //删除员工需要先删除中间表信息
        employeeMapper.deleteRelation(id);
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional
    public void insert(Employee employee, Long[] ids) {
        //更新员工信息
        employeeMapper.insert(employee);
        //添加关系表信息
        if (ids != null && ids.length > 0){
            employeeMapper.insertRelation(employee.getId(),ids);
        }
    }

    @Override
    public Employee listOne(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    @Override
    @Transactional
    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);
        //先删除员工关系表中的信息
        employeeMapper.deleteRelation(employee.getId());
        //添加关系表信息
        if (ids != null && ids.length > 0) {
            employeeMapper.insertRelation(employee.getId(), ids);
        }
    }
    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        //开始分页,传入当前页跟每页显示数据的大小
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Employee>  data = employeeMapper.selectForList(qo);
        return new PageInfo<Employee>(data);
    }

    @Override
    public void batchDelete(Long[] ids) {
        //批量删除先删除中间表信息
        employeeMapper.batchDeleteRelation(ids);
        employeeMapper.batchDelete(ids);
    }
    @Override
    public Employee login(String username, String password)  {
        //判空
        if (!StringUtils.hasText(username)) {
            throw new LogicException("用户名不能为空");
        }
        if (!StringUtils.hasText(username)) {
            throw new LogicException("密码不能为空");
        }
        Employee employee = employeeMapper.checkNameAndPassword(username, password);
        if (employee == null) {
            throw new LogicException("账号或者密码有误");
        }
        if (!employee.isStatus()){
            throw new LogicException("账号已被禁用,请联系管理员");
        }
        return employee;
    }

    @Override
    public Employee selectByName(String username) {
        return employeeMapper.selectByName(username);
    }

    @Override
    public Workbook exportXls(String keyword, Long deptId) {
        List<Employee> employees = employeeMapper.selectByKeywordAndDeptId(keyword,deptId);
        //创建excel对象
        HSSFWorkbook wb = new HSSFWorkbook();
        //创建表格
        HSSFSheet sheet = wb.createSheet();
        //创建行
        HSSFRow row = sheet.createRow(0);
        //创建单元格
        row.createCell(0).setCellValue("用户名");
        row.createCell(1).setCellValue("真实姓名");
        row.createCell(2).setCellValue("密码");
        row.createCell(3).setCellValue("邮箱");
        row.createCell(4).setCellValue("年龄");
        row.createCell(5).setCellValue("部门");
        for (int i = 0; i < employees.size(); i++){
            //获取员工对象
            Employee employee = employees.get(i);
            HSSFRow row1 = sheet.createRow(i + 1);
            row1.createCell(0).setCellValue(employee.getUsername());
            row1.createCell(1).setCellValue(employee.getName());
            row1.createCell(2).setCellValue(employee.getPassword());
            row1.createCell(3).setCellValue(employee.getEmail());
            if (employee.getAge() != null) {
                row1.createCell(4).setCellValue(employee.getAge());
            }
            row1.createCell(5).setCellValue(employee.getDept().getName());
        }
        return wb;
    }

    @Override
    public JsonResult importXls(MultipartFile file) throws IOException {
        int successCount = 0;
        int failureCount = 0;
        StringBuilder str = new StringBuilder();
        List<String> usernames = employeeMapper.selectAllUsernames();
        //获取Workbook
       Workbook wb = new HSSFWorkbook(file.getInputStream());
       //获取第一张表
        Sheet sheet = wb.getSheetAt(0);
        //获取最后一列
        int lastRowNum = sheet.getLastRowNum();
        for (int i = 1; i <= lastRowNum; i++){
            Employee employee = new Employee();
            //读取第一列数据
            Row row = sheet.getRow(i);
            String username = row.getCell(0).getStringCellValue();
            if (usernames.contains(username)){
                try {
                    throw new LogicException("第" + i + "行数据,用户名重复");
                }catch (Exception e){
                    //出现异常.异常信息数量加1
                    failureCount ++;
                    //将异常信息进行拼接
                    str.append(e.getMessage() + "<br/>");
                    e.printStackTrace();
                    continue;
                }
            }
            usernames.add(username);
            employee.setUsername(username);
            employee.setName(row.getCell(1).getStringCellValue());
            employee.setPassword(row.getCell(2).getStringCellValue());
            employee.setAge((int)row.getCell(3).getNumericCellValue());
            employee.setEmail(row.getCell(4).getStringCellValue());
            employeeMapper.insert(employee);
            //成功导入,则成功次数加1
            successCount++;
        }
            return new JsonResult(successCount,failureCount,str.toString());
    }

    @Override
    public void updateEmpStatus(Long id) {
        employeeMapper.updateEmpStatus(id);
    }

    @Override
    public int countNoReadMessageById(Long id) {
        return employeeMapper.countNoReadMessageById(id);
    }
}
